package org.footito.android.ui.adapters;

import java.util.ArrayList;

import org.footito.android.R;
import org.footito.android.data.Comment;
import org.footito.android.data.Status;
import org.footito.android.data.database.FootitoDatabaseAdapter;
import org.footito.android.tools.Log;
import org.footito.android.ui.activity.TimelineFragment.OnStatusClickedListener;
import org.footito.android.ui.views.CounterView;
import org.footito.android.ui.views.InformationView;

import android.content.Context;
import android.os.AsyncTask;
import android.text.Html;
import android.text.Spanned;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class TimelineAdapter extends BaseExpandableListAdapter implements
		OnStatusClickedListener {

	private FootitoDatabaseAdapter dbAdapter;
	private ArrayList<Status> statusList = new ArrayList<Status>();
	private Context context;
	private ListView list;
	private int addedCount = 0;
	private OnStatusClickedListener mOnStatusClickedListener;
	private long mBaseTimestamp = System.currentTimeMillis();
	private int mPage = -1;
	private int mPageLimit = 10;
	private LoadMoreStatus mLoadMoreStatusTask;
	public boolean mEnded = false;

	public TimelineAdapter(Context context, ListView list) {
		dbAdapter = FootitoDatabaseAdapter.getInstance(context);
		loadMoreStatus();
		this.context = context;
		this.list = list;
	}

	public void loadMoreStatus() {
		Log.d("Start Load More " + mLoadMoreStatusTask);
		if (mLoadMoreStatusTask == null) {
			Log.d("New Load More " + mLoadMoreStatusTask);
			mLoadMoreStatusTask = new LoadMoreStatus();
			Log.d("Execute Load More " + mLoadMoreStatusTask);
			mLoadMoreStatusTask.execute();
		}
	}

	@Override
	public Object getChild(int groupPosition, int childPosition) {
		return statusList.get(groupPosition).getComments()
				.get(childPosition - 1);
	}

	@Override
	public long getChildId(int groupPosition, int childPosition) {
		try {
			Status status = statusList.get(groupPosition);
			Comment comment = status.getComments().get(childPosition - 1);
			return comment.getId();
		} catch (Exception e) {
			Log.e(e);
			return 0;
		}
	}

	@Override
	public View getChildView(int groupPosition, int childPosition,
			boolean isLastChild, View convertView, ViewGroup parent) {
		if (childPosition == 0) {
			convertView = new InformationView(context, this);
			((InformationView) convertView).setStatus(statusList
					.get(groupPosition));
		} else {
			convertView = LayoutInflater.from(context).inflate(
					R.layout.row_comment, null);
			TextView tv_comment = (TextView) convertView
					.findViewById(R.id.tv_comment);
			ArrayList<Comment> commentsList = statusList.get(groupPosition)
					.getComments();
			if (childPosition - 1 < 3 || commentsList.size() == 4) {
				Comment comment = commentsList.get(childPosition - 1);
				Spanned text = Html.fromHtml("<b>"
						+ comment.getTeam().getName() + "</b> : "
						+ comment.getContent());
				tv_comment.setText(text);
			} else {
				Spanned text = Html.fromHtml("<b>...</b>");
				tv_comment.setText(text);
				tv_comment.setGravity(Gravity.CENTER);
			}
		}
		return convertView;
	}

	@Override
	public int getChildrenCount(int groupPosition) {
		if (groupPosition == getGroupCount() - 1) {
			return 0;
		} else {
			if (statusList.get(groupPosition).getComments().size() <= 4) {
				return statusList.get(groupPosition).getComments().size() + 1;
			} else {
				return 4 + 1;
			}
		}
	}

	@Override
	public Object getGroup(int groupPosition) {
		// Prevent from empty list
		if (statusList.size() < 1) {
			return null;
		}

		if (groupPosition == getGroupCount() - 1) {
			return null;
		} else {
			return statusList.get(groupPosition);
		}
	}

	@Override
	public int getGroupCount() {
		int count = statusList.size();
		if (!mEnded)
			count++;
		return count;
	}

	@Override
	public long getGroupId(int groupPosition) {
		if (groupPosition == getGroupCount() - 1) {
			return -1;
		} else {
			return statusList.get(groupPosition).getId();
		}
	}

	@Override
	public View getGroupView(int groupPosition, boolean isExpanded,
			View convertView, ViewGroup parent) {
		RowHolder holder = null;
		if (convertView == null) {
			convertView = View.inflate(context, R.layout.row_timeline, null);
			holder = new RowHolder();
			holder.layoutDisplayed = convertView
					.findViewById(R.id.layoutDisplayed);
			holder.tv_status = (TextView) convertView
					.findViewById(R.id.TV_Team_Status);
			holder.iv_flag = (ImageView) convertView.findViewById(R.id.IV_Flag);
			holder.counterView = (CounterView) convertView
					.findViewById(R.id.counterView);
			holder.pb_waiting = (ProgressBar) convertView
					.findViewById(R.id.pb_waiting);
			convertView.setTag(holder);
		} else {
			holder = (RowHolder) convertView.getTag();
		}

		if (groupPosition == getGroupCount() - 1 && !mEnded) {
			holder.pb_waiting.setVisibility(View.VISIBLE);
			holder.layoutDisplayed.setVisibility(View.GONE);
			loadMoreStatus();
		} else {
			holder.pb_waiting.setVisibility(View.GONE);
			holder.layoutDisplayed.setVisibility(View.VISIBLE);
			Status status = statusList.get(groupPosition);
			holder.tv_status.setText(status.getContent());
			holder.tv_status.setText(Html.fromHtml("<b>"
					+ status.getTeam().getName() + "</b> : "
					+ status.getContent()));
			holder.iv_flag.setImageBitmap(status.getTeam().getPicture(context));
			holder.counterView.setCounter(status.getComments().size());
		}
		return convertView;
	}

	@Override
	public boolean hasStableIds() {
		return false;
	}

	@Override
	public boolean isChildSelectable(int groupPosition, int childPosition) {
		return false;
	}

	public void setOnStatusClickedListener(OnStatusClickedListener listener) {
		mOnStatusClickedListener = listener;
	}

	@Override
	public void onStatusClicked(Status status) {
		if (mOnStatusClickedListener != null)
			mOnStatusClickedListener.onStatusClicked(status);
	}

	private class RowHolder {

		public ProgressBar pb_waiting;
		public CounterView counterView;
		public ImageView iv_flag;
		public TextView tv_status;
		public View layoutDisplayed;

	}

	private class LoadMoreStatus extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			ArrayList<org.footito.android.data.Status> statusListResult = dbAdapter
					.getStatusByPage(mBaseTimestamp, mPage, mPageLimit);
			if (statusListResult.size() > 0) {
				mPage++;
				mEnded = false;
			} else {
				mEnded = true;
			}
			statusList.addAll(statusListResult);
			addedCount = statusListResult.size();
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			int position = list.getFirstVisiblePosition();
			TimelineAdapter.this.notifyDataSetChanged();
			// list.setSelection(position + addedCount);
			addedCount = 0;
			mLoadMoreStatusTask = null;
		}
	}

}
